<?php
ignore_user_abort(true);
set_time_limit(0);
date_default_timezone_set('Asia/Shanghai');
require_once 'mysql.php';
$mysql = new Database("127.0.0.1", "root", "123100", "wlw");
$servsock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (FALSE === $servsock) {
    $errcode = socket_last_error();
    fwrite(STDERR, "socket create fail: " . socket_strerror($errcode));
    exit(-1);
}

if (!socket_bind($servsock, '0.0.0.0', 8080)) {
    $errcode = socket_last_error();
    fwrite(STDERR, "socket bind fail: " . socket_strerror($errcode));
    exit(-1);
}

if (!socket_listen($servsock, 128)) {
    $errcode = socket_last_error();
    fwrite(STDERR, "socket listen fail: " . socket_strerror($errcode));
    exit(-1);
}

$clients = array();
$read_socks = array();
$write_socks = array();
$except_socks = NULL;

$read_socks[] = $servsock;

$connsock = null;

function removeClient($clientSocket)
{
    global $read_socks, $write_socks, $clients, $mysql;
    foreach ($read_socks as $key => $val) {
        if ($val == $clientSocket) unset($read_socks[$key]);
    }

    foreach ($write_socks as $key => $val) {
        if ($val == $clientSocket) unset($write_socks[$key]);
    }

    foreach ($clients as $key => $val) {
        if ($val == $clientSocket) {
            if ($key == $mysql->selectDataCONNSOCK($key)) {
                $mysql->deleteData($key);
            }
            unset($clients[$key]);
        }
    }
}

while (1) {
    $tmp_reads = $read_socks;
    $tmp_writes = $write_socks;

    $count = socket_select($tmp_reads, $tmp_writes, $except_socks, NULL);

    foreach ($tmp_reads as $read) {
        if ($read == $servsock) {
            $connsock = socket_accept($servsock);
            if ($connsock) {
                socket_getpeername($connsock, $addr, $port);
                echo "client connect server: ip = $addr, port = $port" . PHP_EOL;

                $clientId = uniqid();
                $clients[$clientId] = $connsock;

                $read_socks[] = $connsock;
                $write_socks[] = $connsock;
            }
        } else {
            try {
                $data = socket_read($read, 1024);
                var_dump($data); // 输出接收到的数据，供调试使用
                if ($data === false) {
                    $error = error_get_last();
                    throw new Exception($error['message']);
                }
            } catch (Exception $e) {
                echo "Error: " . $e->getMessage() . PHP_EOL;
                removeClient($read);
                socket_close($read);
                continue;
            }

            if ($data === '') {
                removeClient($read);
                socket_close($read);
                echo "client close" . PHP_EOL;
            } else {
                $jsData = json_decode($data);
                $yhId = null;
                if (json_last_error() === JSON_ERROR_NONE) {
                    $sbId = $jsData->id;
                    $sbHuiFu = $jsData->fh;
                    if ($sbHuiFu === 1) {
                        socket_getpeername($read, $addr, $port);  //获取远程客户端ip地址和端口
                        foreach ($clients as $clientId => $clientSocket)//用于遍历数组或集合
                        {
                            $clientAddr = '';
                            $clientPort = 0;
                            socket_getpeername($clientSocket, $clientAddr, $clientPort);
                            if ($clientAddr == $addr && $clientPort == $port) {
                                if ($sbId != $mysql->selectDataSBID($sbId) && $sbId != null)//查询
                                {
                                    $mysql->insertData($sbId, $clientId);//增加

                                } else {
                                    $mysql->updateData($sbId, $clientId);//修改
                                }
                                // 找到了匹配的客户端标识符
                                //echo "read 0002 # $clientId # $clientSocket # $addr:$port # " . $data . "\n";
                                sb_id_chu_li($jsData); // 将客户端标识符传递给 chul 函数进行处理

                            }
                        }
                    } else {
                        sb_id_chu_li($jsData); // 将客户端标识符传递给 sb_id_chu_li 函数进行处理
                    }
                } else {
                    echo $data;
                    echo "解析失败，错误信息：  " . json_last_error_msg();
                }


                /*
                // 处理数据逻辑
                $targetConnectionId = null;
                $sbid =null;
                $targetConnection = null;
                if (startsWith($data, 'SBID\\')) {//代码检查请求是否以"SBID "开头，即以"SEND "作为命令的前缀。
                    $parts = explode('\\', $data);//如果请求以"SBID "开头，则代码使用空格拆分请求字符串，并将其存储在 `$parts` 数组中。
                    $sbid = $parts[1];
                    socket_getpeername($read, $addr, $port);  //获取远程客户端ip地址和端口
                    foreach ($clients as $clientId => $clientSocket)//用于遍历数组或集合
                    {
                        $clientAddr = '';
                        $clientPort = 0;
                        socket_getpeername($clientSocket, $clientAddr, $clientPort);
                        if ($clientAddr == $addr && $clientPort == $port) {
                            if($sbid != $mysql->selectDataSBID($sbid) && $sbid != null)//查询
                            {
                                $mysql->insertData($sbid,$clientId);//增加

                            }else{
                                $mysql->updateData($sbid,$clientId);//修改
                            }
                            // 找到了匹配的客户端标识符
                            //echo "read 0002 # $clientId # $clientSocket # $addr:$port # " . $data . "\n";
                            chul($data); // 将客户端标识符传递给 chul 函数进行处理
                            break;
                        }
                    }
                }else{
                    chul($data); // 将客户端标识符传递给 chul 函数进行处理
                }  */
            }
        }
    }
}

socket_close($servsock);

/*
 $data = array(
    'name' => 'John',
    'age' => 30,
    'email' => 'john@example.com'
);
$jsonData = json_encode($data);
echo $jsonData;

$jsonData  =  '{"name":  "John",  "age":  30,  "email":  "john@example.com"}';
$data  =  json_decode($jsonData);
if  (json_last_error()  ===  JSON_ERROR_NONE)  {
     echo  "解析成功！";
     echo  "姓名：  "  .  $data->name  .  "<br>";
     echo  "年龄：  "  .  $data->age  .  "<br>";
     echo  "电子邮件：  "  .  $data->email  .  "<br>";
}  else  {
     echo  "解析失败，错误信息：  "  .  json_last_error_msg();
}
 * */

// 其他函数和处理逻辑
// php ser.php

// 辅助函数：判断字符串是否以指定前缀开头
function startsWith($haystack, $needle)
{
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}

function sb_id_chu_li($json)
{

}

function chul($data)
{
    global $clients, $mysql; // 引用全局变量 $clients，以便在函数内部使用
    $leiXing = null;
    $sbid = null;
    //$targetConnection = null;
    if (startsWith($data, 'SEND\\')) {//代码检查请求是否以"SEND "开头，即以"SEND "作为命令的前缀。
        $parts = explode('\\', $data);//如果请求以"SEND "开头，则代码使用\拆分请求字符串，并将其存储在 `$parts` 数组中。
        $leiXing = $parts[1];//从$parts数组中取出索引为1的元素（即第二个元素），并将其赋值给$leiXing
        $sbid = $parts[2];//从$parts数组中取出索引为2的元素（即第三个元素），并将其赋值给$sbid
    }
    switch ($leiXing) {
        case "diyi":
            echo "shi........... bai\n";
            break;
        case "didy":
            foreach ($clients as $clientId => $clientSocket) {
                socket_write($clientSocket, "你喜欢的颜色是啥色?\n", strlen("你喜欢的颜色是啥色?\n"));
            }
            break;
        case "didd":
            $as = $mysql->selectDataSBID($sbid);//返回sbid
            echo "didd....$as..... 1\n";
            if ($sbid == $mysql->selectDataSBID($sbid)) {
                echo "didd........... 2\n";
                $mysql->deleteDataSBID($sbid);//删除
            }
            break;
        case "ddd":
            $targetConnectionId = $mysql->selectData($sbid);//返回uniqid标志符
            if ($targetConnectionId != null) {
                foreach ($clients as $clientId => $clientSocket)//$clientSocket为客户端连接ID
                {
                    if ($targetConnectionId == $clientId) {
                        echo "fa song # $clientSocket # $clientId\n";
                        socket_write($clientSocket, "shuanfj\\dhfjdhf?\n");
                    } else {
                        echo "shi bai\n";
                    }
                }
            }
            break;
        case "shijian":
            $shiJian = time();
            $targetConnectionId = $mysql->selectData($sbid);
            if ($targetConnectionId != null) {
                foreach ($clients as $clientId => $clientSocket) {
                    if ($targetConnectionId == $clientId) {
                        // $mass = ""
                        socket_write($clientSocket, "wwzc\\$shiJian");
                    }
                }
            }
            break;
        default:
            break;
    }
}


//var_dump(time());//获取时间戳
//$dangQianShiJian = time();
// SBID\ss123
// SEND\ddd\ss123
//SEND\didd\ss123
//SEND\shijian\ss123

// php ser.php
